package bp.App.GZSZ;

import bp.App.GZSZ.model.NewCustomerAttr;
import bp.App.GZSZ.model.PM_NewCustomer;
import bp.da.DBAccess;
import bp.da.DataRow;
import bp.da.DataTable;
import bp.da.DataType;
import bp.difference.SystemConfig;
import bp.difference.handler.DirectoryPageBase;
import bp.en.Entity;
import bp.port.Emp;
import bp.port.EmpAttr;
import bp.tools.AesEncodeUtil;
import bp.wf.Dev2Interface;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

public class GZ_CommTS extends DirectoryPageBase{

    /**
     *  客户id，及客户编号的赋值
     *
     * @return
     * @throws Exception
     */
    public String exeCustomerNoCode()
    {
        String No="CR";
        String code="KH";
        try
        {
          String date=DataType.getCurrentDateByFormart("YYMMdd");
          DataTable dt = new DBAccess().RunSQLReturnTable("select count(1) ct from lzmispm.dbo.pm_Customer where CR_ID like '%"+date+"%' union select count(1) from lzmispm.dbo.pm_Customer");
          if(dt.Rows.size()>0){
            int rct=Integer.parseInt(dt.Rows.get(0).getValue("ct").toString())+1;
            int cct=Integer.parseInt(dt.Rows.get(1).getValue("ct").toString())+1;
              No+=date+buqi(rct);
              code+=buqi(cct);
          }else{
              No+=date+"00001";
              code="KH000001";
          }
        }
        catch (Exception ex)
        {
            return "err@获取编号出错" + ex.getMessage();
        }
        return No+","+code;
    }
    private  String buqi( int number ) {
        DecimalFormat df = new DecimalFormat("00000");
        String formatted = df.format(number);
        System.out.println(formatted); // 输出: 00042
        return formatted;
    }
    /**
     *  自动登录
     *
     * @return
     * @throws Exception
     */
    public String getGZUserInfo()
    {
        String User = this.GetRequestVal("User");
        try
        {
            //AES加密key
//            String key = SystemConfig.GetIsEncryptionKey();
            //User = BP.Tools.AESHelper.AESDecrypt(User, key);
            Emp emp = new Emp();
            //判断帐号
            if (emp.IsExit(EmpAttr.No, User))
            {
                String userToken = "";
                Dev2Interface.Port_Login(emp.getNo());
                userToken = Dev2Interface.Port_GenerToken(emp.getNo());
                return userToken;
            }
        }
        catch (Exception ex)
        {
            return "err@获取用户出错" + ex.getMessage();
        }
        return "err@无此用户:" + User;
    }
    /**
     * 客户信息变更
     *
     * @return
     * @throws Exception
     */
    public String exeCustomerInfoChange()
    {
        try
        {
            //上传的主表字段
            String [] keys={"CR_CreditCode","Name","CR_ID","CR_Name","CR_NameT","CustOpenBank","No","CR_UnitPlace","CR_LegalPerson","CR_TradeType","CR_Telephone","CR_CRType","CR_AccountBank","CR_Province","CR_AccountNumber","CR_FisrstCode","CR_UnitPostCode","CR_Qualification"
            ,"CR_QualityTime","CR_Scope","CR_Staff","MUser","SUser","CR_Fax","CR_Remark","CR_Level","CR_LevelText","CR_ISJTUnit","CR_ISJTUnitText","EntityState"
                    ,"RecName","RecNo","DeptNo","RDT","DeptName","OrgNo","AtPara","CR_Credit","CR_CreditCodeStatus","CR_CreditCodeStatusText","CR_CreditCodeSimilar","CR_TradeTypeT","CR_CRTypeT","CR_ProvinceT"
                    ,"CR_LevelT","CR_ISJTUnitT","CR_CreditCodeStatusT"};
            //上传的天眼查字典
            String [] keys2={"TYC_FromTime","TYC_StaffNumRange","TYC_usedBondName","TYC_RegNumber","TYC_PercentileScore","TYC_RegCapital","TYC_RegInstitute","TYC_Industry","TYC_SocialStaffNum","TYC_Tags","TYC_ToTime","TYC_TaxNumber","TYC_ApprovedTime","TYC_Property3"
                    ,"TYC_Alias","TYC_OrgNumber","TYC_RegStatus","TYC_UpdateTimes","TYC_EstiblishTime","TYC_BondType","TYC_ActualCapital","TYC_CompanyOrgType","TYC_CompForm","TYC_HistoryNames","TYC_HistoryNameList"
                    ,"TYC_BondNum","TYC_RegCapitalCurrency","TYC_ActualCapitalCurrency","TYC_RevokeDate","TYC_RevokeReason","TYC_CancelReason","TYC_CancelDate","TYC_Base","TYC_City","TYC_District","TYC_Category","TYC_CategoryBig","TYC_CategoryMiddle","TYC_CategorySmall"
                    ,"TYC_BondName","TYC_IsMicroEnt","TYC_Type","TYC_CategoryCodeFirst","TYC_CategoryCodeSecond","TYC_CategoryCodeThird","TYC_CategoryCodeFourth","TYC_Email","TYC_EmailList","TYC_WebsiteList"
                    };
            //数据库记录的要检查的字段
            String [] key3={"NC_Unit","NC_Address","NC_Type","NC_Province","NC_FRName","NC_FRPhone"};
            //要检查字段对应的新值存储字段
            String [] key4={"NC_UnitNew","NC_AddressNew","NC_TypeNew","NC_ProvinceNew","NC_FRNameNew","NC_FRPhoneNew"};

            //要检查的字段对应的上传字段
            String [] key5={"CR_Name","CR_UnitPlace","CR_TradeType","CR_Province","CR_LegalPerson","CR_Telephone"};

            //获取客户类别 codetype='pa'    获取客户属性 codetype='khsx'   省份：codetype='XD'
//            DataTable khdt = new DBAccess().RunSQLReturnTable("SELECT Code AS No,Description AS Name,CodeType FROM lzmispm.dbo.S_Code WHERE CodeType in('pa','khsx') or (codetype='XD' and parentcode='-')");

            //必用字段
            String CR_ID=this.GetRequestVal("CR_ID");  //客户id
            //判断是否有社会统一码一样的情况
            DataTable checkTable = new DBAccess().RunSQLReturnTable("SELECT COUNT(*) AS cnt FROM lzmispm.dbo.pm_Customer WHERE CR_CreditCode = '" + this.GetRequestVal("CR_CreditCode") + "' AND CR_ID <> '" + CR_ID + "'");
            if (checkTable.Rows.size() > 0 && Integer.parseInt(checkTable.Rows.get(0).getValue("cnt").toString()) > 0) {
                return "sameCode";
            }

            //修改前数据
            StringBuffer oldSql=new StringBuffer("select ");
            for(String str:key5){
                oldSql.append( str+", ");
            }
            oldSql.append(" '' test from lzmispm.dbo.pm_Customer where CR_ID='"+CR_ID+"'");
            DataTable olddt = new DBAccess().RunSQLReturnTable(oldSql.toString());
            if(olddt.Rows.size()>0){
                PM_NewCustomer nc=new PM_NewCustomer();

                boolean ischange=false;
               for(int i=0;i<key5.length;i++){
                   String oldVal=olddt.Rows.get(0).get(key5[i])!=null?olddt.Rows.get(0).get(key5[i]).toString():"";
                   String newVal=this.GetRequestVal(key5[i]);
//                   String oldvals= "";
//                   String newvals = "";
//                   if(i==2 || i==3){
//                       String  tag="XD";
//                       if(i==2){
//                           tag="pa";
//                       }
//                       newvals=getStr(khdt,newVal,tag);
//                       oldvals=getStr(khdt,oldVal,tag);
//                   }else{
//                       newvals=newVal;
//                       oldvals=oldVal;
//                   }
                   if(!oldVal.equals(newVal)){
                       ischange=true;
                       nc.setValByKey(key3[i],oldVal);
                       nc.setValByKey(key4[i],newVal);
                   }
                }
               //信息发生了改变
               if(ischange){
                   String iid= UUID.randomUUID().toString();
                   nc.setMyPK(iid);
                   nc.setValByKey(NewCustomerAttr.NC_ID,iid);
                   nc.setValByKey(NewCustomerAttr.CR_ID,CR_ID);
                   nc.setValByKey(NewCustomerAttr.RDT,DataType.getCurrentDataTime());
                   //是否集团内
                   nc.setValByKey(NewCustomerAttr.NC_ISJTUnit,this.GetRequestVal("CR_ISJTUnit"));
                   //客户属性
                   nc.setValByKey(NewCustomerAttr.NC_CRType,this.GetRequestVal("CR_CRType"));
                   nc.Insert();
               }
             }
        }
        catch (Exception ex)
        {
            return "err@客户信息变更出错" + ex.getMessage();
        }
        return "success";
    }

    private String getStr(DataTable khdt ,String val,String tag)
    {
        String newvals="";
        if(DataType.IsNullOrEmpty(val))
            return "";
        if(tag.equals("pa")){
            String [] strs=val.split(",");
            for(String str:strs){
               List<DataRow> list= khdt.Rows.stream().filter(j->j.get("CodeType").toString().toLowerCase().equals(tag) && j.get("No").toString().equals(str)).collect(Collectors.toList());
               if(list.size()>0){
                   String newstr= list.get(0).get("Name").toString();
                   newvals+=newstr+",";
               }
            }
            if(!DataType.IsNullOrEmpty(newvals)){
                newvals=newvals.substring(0,newvals.length()-1);
            }
        }else{
            List<DataRow> list= khdt.Rows.stream().filter(j->j.get("CodeType").toString().toLowerCase().equals(tag) && j.get("No").toString().equals(val)).collect(Collectors.toList());
            if(list.size()>0){
                String newstr= list.get(0).get("Name").toString();
                newvals=newstr;
            }
        }
        return newvals;
    }
    /**
     * 客户等级处理
     *
     * @return
     * @throws Exception
     */
    public String exeCR_Level()
    {
        String CR_ID=this.GetRequestVal("CR_ID");  //客户id
        //获取天眼查有数据的客户，包含合同数量
        String sql="select ISNULL(sum(CT_Money),0) from lzmispm.dbo.PM_Contract where  CHARINDEX('"+CR_ID+"',CT_FirstSide) >0  ";
        DataTable table = DBAccess.RunSQLReturnTable(sql);
        double money=0;
        if(table.Rows.size()>0){
            money=bp.difference.context.XSSSafeDoubleParser.parse(table.Rows.get(0).getValue(0).toString());
            if(money>0)
            return  "success";
        }
        return  "faile";
    }
    public static void main(String[] args) {
      String a=  getCurrentDateByFormart("YYMMdd");
        System.out.println(a);
    }
    public static String getCurrentDateByFormart(String formart) {
        Date dt = new Date();
        SimpleDateFormat matter = new SimpleDateFormat(formart);
        String date = matter.format(dt);
        return date;
    }
    /// <summary>
    /// 插入之前
    /// </summary>
    /// <param name="frmID"></param>
    /// <param name="no"></param>
    /// <param name="en"></param>
    /// <returns></returns>
    public static String FrmEntity_BeforeInsert(String frmID, String No, Entity en)
    {
        if (SystemConfig.getCustomerNo().equals("GZSZ"))
        {
            if (frmID.equals("En_KeHuXinXiTaiZhang"))
            {
                GZ_CommTS gc = new GZ_CommTS();
                String str = gc.exeCustomerNoCode();
                en.SetValByKey("CR_ID", str.split(",")[0]);
                en.SetValByKey("CR_Code", str.split(",")[1]);
                en.SetValByKey("No",str.split(",")[0]);
                en.SetValByKey("EntityState",2);
            }
        }
        return null;
    }

}
